<template>
  <div class="upload-agreement">
    <h3>上传解除协议图片</h3>
    <el-form ref="formRef" :model="form" label-width="80px" :rules="formRules">
      <el-form-item label="合同编号">
        <el-input v-model="form.contractNo" disabled placeholder="合同编号" />
      </el-form-item>
      <el-form-item label="解除日期" prop="terminationTime" required>
        <el-date-picker v-model="form.terminationTime" type="date" placeholder="选择解除日期" style="width: 100%;"
          :disabled="isSubmitting || !hasContractData" :disabled-date="disableContractDates" />
        <div class="el-upload__tip" style="margin-top: 8px; color: #67C23A;" v-if="hasContractData">
          合同期限：{{ form.startDate }} 至 {{ form.endDate }}
        </div>
        <div class="el-upload__tip" style="margin-top: 8px; color: #F56C6C;" v-else>
          {{ contractLoadError || '加载合同信息中...' }}
        </div>
      </el-form-item>
      <el-form-item label="解除协议图片" prop="terminationAgreement" required>
        <image-upload v-model="form.terminationAgreement" :disabled="isSubmitting || !hasContractData" :limit="1"
          :before-upload="beforeFileUpload" @exceed="handleExceed" @error="handleUploadError" />
        <div class="el-upload__tip" style="margin-top: 8px;">
          请上传JPG/PNG格式图片，大小在10M以内
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import ImageUpload from '@/components/ImageUpload/index.vue';
import { useUserStore } from '@/store/modules/user'
import { tuizhuaddAccraditationRecord } from '@/api/le/accraditationRecord';
import { listContract, updateContract } from "@/api/le/contract";
import { useRouter } from "vue-router";
// 获取路由实例
const router = useRouter();


const { proxy } = getCurrentInstance();
const userStore = useUserStore();

// 表单数据
const form = reactive({
  contractNo: '',
  terminationTime: '',  // 解除日期（日期选择器值）
  terminationAgreement: '',
  approverId: userStore.id,
  startDate: '',
  endDate: '',
  id: null
});

// 父组件参数
const props = defineProps({
  Lastfrom: {
    type: Object,
    required: true
  }
});

// 状态管理
const formRef = ref(null);
const isSubmitting = ref(false);
const hasContractData = ref(false); // 是否获取到有效合同数据
const contractLoadError = ref(''); // 合同加载错误信息

// 1. 日期格式化工具：转为后端要求的 yyyy-MM-dd HH:mm:ss
const formatToBackendDate = (dateInput) => {
  if (!dateInput) return '';
  // 处理日期选择器的字符串值或Date对象
  const date = typeof dateInput === 'string' ? new Date(dateInput) : dateInput;
  if (isNaN(date.getTime())) {
    ElMessage.error('无效的日期格式');
    return '';
  }

  const padZero = (num) => num.toString().padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`;
};

// 2. 加载合同信息（带错误处理）
const loadContractData = async () => {
  try {
    const response = await listContract({ elderlyId: props.Lastfrom.extraField2,contractStatus: "生效中" });
    if (response.rows && response.rows.length > 0) {      
      const contract = response.rows[0];
            // console.log("获取的合同信息",contract);
      form.id = contract.id;
      form.contractNo = contract.contractNo;
      form.startDate = contract.startDate;
      form.endDate = contract.endDate;
      hasContractData.value = true;
      contractLoadError.value = '';
    } else {
      hasContractData.value = false;
      contractLoadError.value = '未查询到相关合同信息，无法继续操作';
      ElMessage.warning(contractLoadError.value);
    }
  } catch (error) {
    hasContractData.value = false;
    contractLoadError.value = `合同信息加载失败：${error.message || '网络异常'}`;
    ElMessage.error(contractLoadError.value);
  }
};

// 初始化加载合同数据
loadContractData();

// 3. 日期禁用逻辑：同时满足「不能早于今天」和「在合同期限内」
const disableContractDates = (time) => {
  const currentDate = new Date(time);
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 清除时间部分

  // 条件1：禁用早于今天的日期
  const isBeforeToday = currentDate < today;

  // 条件2：禁用合同期限外的日期（如果有合同数据）
  let isOutOfContractDate = false;
  if (form.startDate && form.endDate) {
    const startDate = new Date(form.startDate);
    const endDate = new Date(form.endDate);
    startDate.setHours(0, 0, 0, 0);
    endDate.setHours(0, 0, 0, 0);
    isOutOfContractDate = currentDate < startDate || currentDate > endDate;
  }

  return isBeforeToday || isOutOfContractDate;
};

// 表单校验规则
const formRules = reactive({
  terminationTime: [
    { required: true, message: '请选择解除日期', trigger: 'change' }
  ],
  terminationAgreement: [
    { required: true, message: '请上传解除协议图片', trigger: 'change' }
  ]
});

// 图片上传校验
const beforeFileUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isImage) { ElMessage.error('请上传JPG或PNG格式的图片'); return false; }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) { ElMessage.error('图片大小不能超过10MB'); return false; }
  return true;
};

const handleExceed = () => ElMessage.warning('只能上传一张解除协议图片');
const handleUploadError = (err) => ElMessage.error(`图片上传失败：${err.message || '未知错误'}`);


//提交逻辑
const handleSubmit = async () => {
  return new Promise((resolve, reject) => {
    // 第一步：表单校验（与第一段一致的校验方式）
    formRef.value.validate((valid) => {
      if (!valid) {
        reject(new Error('请完善表单信息'));
        return;
      }

      // 第二步：设置加载状态，防止重复提交
      isSubmitting.value = true;

      // 第三步：构造提交数据（agreementFile传递图片地址，与第一段图片逻辑一致）
      const submitData = {
        ...form,
        // 补充父组件传递的业务参数（保留原有逻辑）
        handleType: props.Lastfrom.id,
        extraField1: props.Lastfrom.taskId,
        bussniessId: props.Lastfrom.bussniessId,
        extraField2: props.Lastfrom.extraField2,
        type: props.Lastfrom.type,
        createTime: props.Lastfrom.createTime,  // 用当前时间，避免依赖父组件时间
        createBy: props.Lastfrom.applicatId,
        stepNo: props.Lastfrom.stepNo,
        approverId: props.Lastfrom.assigneeId,
        auditStatus: 1,
        terminationTime: formatToBackendDate(form.terminationTime),
        terminationSubmitter:userStore.id,
        opinion: "同意",
        creator: userStore.id,
        creator1: userStore.nickName  // 与第一段一致，记录创建人
      };
      // console.log("form:::::::::",form);
      
      // console.log("submitData::::::",submitData);
      
      // 第四步：调用接口提交（此处示例用若依modal提示，与第一段一致）
      // 注意：需替换为实际的“解除协议图片提交接口”，示例暂用addContract模拟
      updateContract(submitData).then(response => {
        proxy.$modal.msgSuccess("解除协议图片上传成功");
          //添加审批记录
          tuizhuaddAccraditationRecord(submitData).then(response => {
            console.log("调用添加审批记录");
          proxy.$modal.msgSuccess("新增成功")

           router.push({ path: "/xietong/pendingTasks", 
             });
        })
        isSubmitting.value = false;
        // 提交成功后重置表单（参考第一段reset逻辑）
        formRef.value.resetFields();
        form.agreementFile = '';
        resolve(submitData);  // 向父组件返回成功数据

      }).catch(error => {
        proxy.$modal.msgError("上传失败，请稍后重试");
        isSubmitting.value = false;
        reject(error);  // 向父组件返回错误信息
      });
    });
  });
};
defineExpose({ handleSubmit, getFormData: () => form });
</script>

<style scoped>
.upload-agreement {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

h3 {
  margin: 0 0 20px;
  color: #1f2329;
  font-size: 18px;
  font-weight: 500;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
}

:deep(.el-form-item__content) .el-upload__tip[style*="color: #67C23A"] {
  font-size: 12px;
  margin-top: 4px;
}

:deep(.el-form-item__content) .el-upload__tip[style*="color: #F56C6C"] {
  font-size: 12px;
  margin-top: 4px;
}
</style>